package cn.edu.hhu.servlet.student;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
 * @anthor: lddd
 * @date: 2020/5/3 - 22:13
 * @description:
 **/
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {

    private Random r = new Random();
    private Color randomColor() {
        int red = r.nextInt(150);
        int green = r.nextInt(150);
        int blue = r.nextInt(150);
        return new Color(red, green, blue);
    }
    private Font randomFont () {
        //int index = r.nextInt(fontNames.length);
        String fontName = "Consolas";
        int style = r.nextInt(4);
        int size = r.nextInt(5) + 24;
        return new Font(fontName, style, size);//指定字体名称、样式和点大小，创建一个新 Font。
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("生成验证码");
        int width = 130;
        int height = 50;
        //1创建图像
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
        //2美化图片
        //2.1填充背景色
        Graphics g = image.getGraphics();
        g.setColor(Color.pink);
        //g.setColor(Color.pink);
        g.fillRect(0, 0, width, height);
        //2.2画边框
        g.setColor(Color.blue);
        g.drawRect(0, 0, width, height);
        //2.3写验证码
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        String verifycode = "";
        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(str.length());
            //获取字符
            g.setColor(randomColor());
            g.setFont(randomFont());
            char ch = str.charAt(index);
            verifycode += ch;
            g.drawString(ch + "", width / 5 * i + 20, height / 2);
        }
        request.getSession().setAttribute("verifycode", verifycode);//存储验证码
        //2.4画干扰线
        g.setColor(Color.green);
        for (int i = 0; i < 10; i++) {
            int x1 = random.nextInt(width);
            int x2 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int y2 = random.nextInt(height);
            g.drawLine(x1, y1, x2, y2);
        }

        //3输出到页面
        ImageIO.write(image, "jpg", response.getOutputStream());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
